package com.qianbei.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerControl.ServerListener;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.ConstantValue;
import com.qianbei.common.utilis.IDCard;
import com.qianbei.common.utilis.Util;
import com.qianbei.user.login.CountryCodeActivity;
import com.qianbei.view.LoginActivity;

public class FindPasswdActivity extends BaseActivity {
    private EditText et_mobile, et_identifyingCode, et_password;
    private TextView tv_identifyingCode;
    private String str_mobile, str_identifyingCode, str_password, strPassAgain;

    private TextView mCountryNumberTv;

    private String mCountryCode = "86";
    private String mCountryName = "中国";
    private EditText mEtPassWordAgain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_findpass);
        initWidget();
        setTitle("找回密码");
    }

    private void initWidget() {
        et_mobile = (EditText) findViewById(R.id.et_mobile);
        et_identifyingCode = (EditText) findViewById(R.id.et_identifyingCode);
        et_password = (EditText) findViewById(R.id.et_password);
        mEtPassWordAgain = (EditText) findViewById(R.id.et_password_again);
        mCountryNumberTv = (TextView) findViewById(R.id.tv_country_number);

        findViewById(R.id.btn_register).setOnClickListener(this);
        tv_identifyingCode = (TextView) findViewById(R.id.tv_identifyingCode);
        tv_identifyingCode.setOnClickListener(this);
        mCountryNumberTv.setOnClickListener(this);
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 22:
                    tv_identifyingCode.setText(msg.arg1 + "秒后重新获取");

                    if (msg.arg1 == 0) {
                        tv_identifyingCode.setClickable(true);
                        tv_identifyingCode.setText("获取验证码");
                    } else {
                        Message msgs = new Message();
                        msgs.arg1 = msg.arg1 - 1;
                        msgs.what = 22;
                        handler.sendMessageDelayed(msgs, 1000);
                    }

                    break;

                default:
                    break;
            }

        }
    };

    public void onClick(View v) {
        String msg;
        switch (v.getId()) {

            case R.id.btn_register:
                msg = checkUserInputValues(false);
                if (!"0".equals(msg)) {
                    new MsgAlert().show(msg);
                    return;
                } else {
                    ForgetPwd(str_mobile, str_identifyingCode, str_password, strPassAgain);
                    Util.hideSoftInputFromWindow(v);
                }
                break;
            case R.id.tv_identifyingCode:

                msg = checkUserInputValues(true);
                // String msg = "0";
                if (!"0".equals(msg)) {
//				DialogUtils.showAlertMsg(mContext, msg);
                    new MsgAlert().show(msg);
                    return;
                } else {
                    // 获取注册验证码
                    registerCheck(str_mobile);
                    Util.hideSoftInputFromWindow(v);
                }

                break;
            case R.id.tv_country_number:
                startActivityForResult(new Intent(this, CountryCodeActivity.class), 1);
                break;

            default:
                break;
        }

    }

    /**
     * 获取注册验证码 1:注册、2:忘记密码、3:更换手机号
     *
     * @param mobile
     */
    private void registerCheck(String mobile) {
        ServerControl sc = new ServerControl(FORGET_PASSWORD_AUTH_CODE,
                "mobile", mobile);
        sc.serverListener = new ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    new MsgAlert().show(sr.bodyData.optString("msg"));

                    //发送验证码
                    Message msgs = new Message();
                    msgs.arg1 = 60;
                    msgs.what = 22;
                    handler.sendMessageDelayed(msgs, 1000);
                    tv_identifyingCode.setClickable(false);
                }
            }
        };
        new ProgressDialog(mContext).startControl(sc, "获取验证码");
    }

    // 重置密码
    private void ForgetPwd(final String mobile, String mobilecode,
                           String password, String strPassAgain) {
        ServerControl sc = new ServerControl(FORGET_PASSWORD,
                "mobile", mobile,
                "mobilecode", mobilecode,
                "password", password,
                "repassword", strPassAgain);
        sc.serverListener = new ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.exception != null) {
                    new MsgAlert().show(mContext
                            .getString(R.string.common_toast_net_not_connect));
                    return;
                }
                if (sr.isContinue) {
                    if (sr.bodyData.optString("flag").equals("0")) {
//                         Intent intent = new Intent(mContext,
//                         SetPasswordActivity.class);
//                         intent.putExtra("phone", mobile);
//                         startActivity(intent);
                    } else {
                        if (sr.bodyData.optJSONObject("data") != null) {
                            SetData.setUserID(sr.bodyData.optJSONObject("data").optString("tok"));
                        }
                        new MsgAlert().show(sr.bodyData.optString("msg"));

                        startActivity(new Intent(mContext, LoginActivity.class));
                        finish();
                    }
                }
            }
        };
        new ProgressDialog(mContext).startControl(sc, "正在加载...");

    }

    private String checkUserInputValues(boolean isGetRegCode) // 手机号与密码的格式
    {
        str_mobile = et_mobile.getText().toString();
        /** 电话号码验证 */
        if (str_mobile == null || "".equals(str_mobile)) {
            return getString(R.string.menu_login_activity_check_mobile_null);
        }
        if ("86".equals(mCountryCode) && str_mobile.length() != 11) {
            return getString(R.string.menu_login_activity_check_mobile_length);
        }
        if ("86".equals(mCountryCode) && !IDCard.isMobileNO(str_mobile)) {
            return getString(R.string.menu_login_activity_check_mobile_format);
        }
        if (isGetRegCode) {
            return "0";
        }

        str_identifyingCode = et_identifyingCode.getText().toString();
        if (str_identifyingCode == null || "".equals(str_identifyingCode)) {
            return getString(R.string.input_identifying_code);
        }
        str_password = et_password.getText().toString();
        strPassAgain = mEtPassWordAgain.getText().toString();
        if (str_password == null || "".equals(str_password) || strPassAgain == null || "".equals(strPassAgain)) {
            return getString(R.string.menu_login_activity_check_password);
        }
        if (!str_password.equals(strPassAgain)) {
            return getString(R.string.password_error_again);
        }
        if (str_password.length() < 6 || strPassAgain.length() < 6 || str_password.length() > 16 || strPassAgain.length() > 16) {
            return getString(R.string.menu_register_activity_check_password_length_min);
        }
        String regex = "[A-Za-z0-9]+";
        if (!str_password.matches(regex) || !strPassAgain.matches(regex)) {
            return getString(R.string.menu_register_activity_check_password_regex);
        }

        return "0";
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK == resultCode && data != null) {
            mCountryCode = data.getStringExtra(ConstantValue.COUNTRY_CODE_KEY);
            mCountryName = data.getStringExtra(ConstantValue.COUNTRY_NAME_KEY);
            mCountryNumberTv.setText(getString(R.string.country_code_format, mCountryName, mCountryCode));
        }
    }
}